<template>
  <div class="">
    <div class="searchBar">
      <el-form label-width="100px">
        <div style="display:flex;">
          <el-form-item label="订单编号:">
            <el-input size="small" v-model="searchOrderNum"></el-input>
          </el-form-item>
          <el-form-item label="订单时间:">
            <el-date-picker v-model="searchTimeRange" type="datetimerange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" size="small">
            </el-date-picker>
          </el-form-item>

        </div>
      </el-form>
      <div style="display: flex;justify-content: center;">
        <el-button type="primary" class="el-icon-search" style="margin:20px 0 0 10px;" size="medium"
          @click="handleSearch(1)">搜索</el-button>
        <el-button class="el-icon-delete" size="medium" style="margin:20px 0 0 10px;" @click="handleSearch(0)">清空
        </el-button>
        <el-button class="el-icon-date" size="medium" style="margin:20px 0 0 10px;" @click="exportTable">导出表单
        </el-button>
      </div>
    </div>


    <avue-crud ref="crud" :page="page" :data="billsDataList" :table-loading="dataListLoading" :option="tableOption"
      @on-load="getBills" :summary-method='summary'>

      <template slot="service_fee" slot-scope="{row}">
        <div>{{-row.service_fee}}</div>
      </template>

      <template slot="rebateMoney" slot-scope="{row}">
        <div>{{-row.rebateMoney}}</div>
      </template>

      <template slot="menuLeft">
        <div class="withdrawBox">
          <div class="showAmount">
            <span style="font-size:20px">余额：</span>
            <span style="font-size:60px;">{{amount}}</span>
            <span>元</span>
          </div>
          <div v-if="isWithdrawShow"></div>
          <button class="withdrawBtn" @click="openWithdrawWindow">提现</button>
        </div>
      </template>
    </avue-crud>

    <el-dialog title="提现金额" :visible.sync="visible" width="400px">
      <el-form v-loading='loading' :model="dataForm" :rules='dataRule' ref="dataForm">
        <el-form-item label="提现账户：">{{myinfo.cardNumber}}</el-form-item>
        <el-form-item label="持卡人：">{{myinfo.cardOwner}}</el-form-item>
        <el-form-item label="最多提现：">{{amount}}元</el-form-item>
        <el-form-item label="输入提现金额：" prop="cashOutAmount">
          <el-input v-model.number="dataForm.cashOutAmount" type='number'></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="withdraw">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import {
    tableOption
  } from '@/crud/finance/bills'
  export default {
    data() {
      var validateCashOutAmount = (rule, value, callback) => {
        if (Number(this.dataForm.cashOutAmount) > Number(this.amount)) {
          callback(new Error('超出最大提现额度'))
        }
      }

      return {
        amount: 0.00,
        visible: false,
        isWithdrawShow: false,
        tableOption: tableOption,
        billsDataList: [],
        dataListLoading: false,
        loading: false,
        rebateMoneyAmount: null,
        dataForm: {
          cashOutAmount: 0
        },

        searchType: '',
        searchOrderNum: '',
        searchTimeRange: [],

        payStateOptions: [{
          label: '待支付',
          value: {
            orderState: 0,
            status: 1,
          }
        }, {
          label: '待支付',
          value: {
            orderState: 0,
            status: 1,
          }
        }, {
          label: '待支付',
          value: {
            orderState: 0,
            status: 1,
          }
        }, ],

        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          size: 10 // 每页显示多少条
        },
        myinfo: {},
        dataRule: {
          cashOutAmount: [{
              required: true,
              message: '金额不能为空',
              trigger: 'blur'
            },
            {
              validator: validateCashOutAmount,
              trigger: 'blur'
            }
          ]
        }
      }
    },

    mounted() {},

    methods: {
      getBills(page) {
        this.getAmount()
        page = (page === undefined ? this.page : page)
        // this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/finance/page'),
          method: 'get',
          params: this.$http.adornParams(
            Object.assign({
              current: page == null ? this.page.currentPage : page.currentPage,
              size: page == null ? this.page.size : page.pageSize,
            }, this.params), false
          )
        }).then(({
          data
        }) => {
          this.billsDataList = data.records
          this.page.total = data.total
          this.dataListLoading = false
        })
      },

      searchChange(params) {
        if (params.time && params.time.length !== 1) {
          params.startTime = this.dateTimeString(params.time[0]),
            params.endTime = this.dateTimeString(params.time[1])
        }
        delete params.time
        this.getBills(this.page, params)
      },

      handleSearch(state) {
        if (state == 0) {
          this.searchOrderNum = ''
          this.searchOrderState = ''
          this.searchTimeRange = []
          this.getBills()
        } else if (state == 1) {
          var params = {
            orderNumber: this.searchOrderNum,
            startTime: this.searchTimeRange.length !== 0 ? this.dateTimeString(this.searchTimeRange[0]) : '',
            endTime: this.searchTimeRange.length !== 0 ? this.dateTimeString(this.searchTimeRange[1]) : '',
            type: this.searchType
          }
          this.params = params
          this.getBills()
        }
      },
      //格式化日期时间
      dateTimeString(val) {
        let date = new Date(val)
        let D = [
          String(date.getFullYear()),
          date.getMonth() < 9 ? '0' + (date.getMonth() + 1) : String(date.getMonth() + 1),
          date.getDate() < 10 ? '0' + date.getDate() : String(date.getDate()),
          date.getHours() < 10 ? '0' + date.getHours() : String(date.getHours()),
          date.getMinutes() < 10 ? '0' + date.getMinutes() : String(date.getMinutes()),
          date.getSeconds() < 10 ? '0' + date.getSeconds() : String(date.getSeconds())
        ]
        return D.slice(0, 3).join('-') + ' ' + D.slice(3).join(':')
      },

      //获取当前账户余额
      getAmount() {
        this.$http({
          url: this.$http.adornUrl('/finance/getAccount'),
        }).then(({
          data
        }) => {
          // this.amount = data.account%1 === 0?String(data.account)+'.00':String(data.account)
          console.log(data.account)
          this.amount = (data.account).toFixed(2)
          this.rebateMoneyAmount = data.rebateMoneyAmount
        })
      },

      //提现
      withdraw() {
        if (this.dataForm.cashOutAmount > 0 && this.dataForm.cashOutAmount <= this.amount) {
          this.$http({
            url: this.$http.adornUrl('/cashOut/cashoutByShop'),
            params: this.$http.adornParams({
              cashOutMoney: this.dataForm.cashOutAmount
            })
          }).then(() => {
            this.$message({
              type: 'sucess',
              message: "申请已提交，请等待汇款"
            })
            this.visible = false
            this.getAmount()
          })
        }
      },

      summary(params) {
        return ['-', '-', '-', '-', '-', '-', '-', '合计：' + this.rebateMoneyAmount]
      },

      openWithdrawWindow() {
        console.log('openwithdraw running')
        this.loading = true
        this.$http({
          url: this.$http.adornUrl("/shop/shopDetail/getShopDetailInformation"),
          method: 'get',
        }).then(({
          data
        }) => {
          if (data.cardNumber) {
            this.visible = true
            this.loading = false
            this.myinfo = data
          } else {
            this.$message.error('您未绑定银行账户，请先去“个人中心”绑定银行账户')
          }
        })
      },

      exportTable() {
        console.log('exportTable running')
        this.$http({
          url: this.$http.adornUrl('/order/order/getBillExcel'),
          method: 'post',
          params: this.$http.adornParams({
            orderNumber: this.searchOrderNum,
            startTime: this.searchTimeRange.length !== 0 ? this.dateTimeString(this.searchTimeRange[0]) : '',
            endTime: this.searchTimeRange.length !== 0 ? this.dateTimeString(this.searchTimeRange[1]) : '',
            type: this.searchType
          }),
          responseType: 'blob' // 解决文件下载乱码问题
        }).then(({
          data
        }) => {
          var blob = new Blob([data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
          })
          const fileName = '商家账单.xls'
          const elink = document.createElement('a')
          if ('download' in elink) { // 非IE下载
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else { // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
        })
      }
    },
  }
</script>
<style lang="scss" scoped>
  // 自定义样式
  .avue-crud__title {
    justify-content: flex-start;
  }

  .el-range-editor--small .el-range-separator {
    width: 30px;
  }

  .avue-crud .avue-crud__left .el-button,
  .avue-crud .avue-crud__right .el-button,
  .avue-form .avue-crud__left .el-button,
  .avue-form .avue-crud__right .el-button {
    margin-right: 8px;
    margin-bottom: 8px;
    height: 34px;
    align-self: flex-end;
  }

  //提现盒子样式
  .Box {
    display: flex;
  }

  .withdrawBox {
    display: flex;
    align-items: center;
    height: 80px;
  }

  .showAmount {
    height: 80px;
    line-height: 80px;
    width: 70%;
  }

  .withdrawBtn {
    height: 40px;
    width: 100px;
    border: 0;
    border-radius: 3px;
    background-color: #02A1E9;
    text-align: center;
    line-height: 40px;
    color: white;
    margin-left: 50px;
    position: relative;
    top: 10px;
  }

  .el-form-item {
    margin-bottom: 5px;
  }
</style>
